<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var trap = function (height) {
        let maxHeight = 0
        let maxIndex = 0
        let result = 0
        for (let i = 0; i < height.length; i++) {
          if (height[i] > maxHeight) {
            maxHeight = height[i]
            maxIndex = i
          }
        }
        let leftMaxHeight = 0
        let rightMaxHeight = 0
        for (let i = 0; i < maxIndex; i++) {
          leftMaxHeight = Math.max(leftMaxHeight, height[i])
          result += leftMaxHeight - height[i]
        }
        for (let i = height.length - 1; i > maxIndex; i--) {
          rightMaxHeight = Math.max(rightMaxHeight, height[i])
          result += rightMaxHeight - height[i]
        }
        return result
      }
    </script>
  </body>
</html>
